<style scoped>
    .config_main {
        padding: 20px;
        background: #fff;
        box-shadow: 5px 5px 10px #eee;
    }
    .config_main .row-col{
        display: flex;
        flex-direction: row;
        align-items: center;
    }
    .config_main .block {
        display: flex;
        flex-direction: row;
        align-items: center;
        flex-wrap: wrap;
        font-size:14px;
    }

    .config_main .block .left {
        width: 150px;
        color: #999;
        font-size:12px;
    }

    .config_main .block .right {
        display: flex;
        flex-direction: row;
        align-items: center;
    }

    .comm_build_textarea{
        width:950px;
        height:300px;
    }
    .btns{
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        padding-top:30px;
    }
    .item_task{
        width:1200px;
    }
    .item_task .title{
        font-size:25px;
        font-weight: 300;
    }
    .tab-btns{
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
    }
    .tab-btns .btn-item{
        margin-right:10px;
    }
    .build_product{
        
    }
    .build_product .el-dialog__body{
        padding-top:5px;
    }
    .build_content{
        display: flex;
        flex-direction: column;
    }
    .build_content .top{
    }
    .build_content .top .table .cell{
        white-space: nowrap;
    }
    .build_content .top .table td, .el-table th {
        padding: 5px 0;
    }
    .build_content .bottom{
        width:calc(100%);
        height:calc(100%);
    }
    .build_content .bottom .shell-terminal{
        width:calc(100%);
        height:650px;
        background:#000;
        position: relative;
    }
    .build_content .bottom .shell-terminal .terminal{
        position: absolute;
        left:10px;
        top:10px;
        width:calc(100% - 40px);
        height:calc(100% - 40px);
        z-index:1;
    }
   
</style>
<div class="content" id="team" v-cloak>
    <el-row>
        <el-col :span="12">
            <div class="grid-content bg-purple com_title">开始构建</div>
        </el-col>
    </el-row>
    <div class="config_main mt30">
        <div class="block">
            <div class="bottom" style="width:100%;">
                <div class="top mb20">资产列表</div>
                <div class="mb10">
                    <el-button @click="serverConfigs()" type="primary" icon="el-icon-tickets" size="medium">脚本任务</el-button>
                    <el-button @click="applicationConsole()" type="danger" icon="el-icon-s-tools" size="medium">控制台</el-button>
                    <span class="ml10 light"><i class="el-icon-warning fs-16 mr5 primary"></i>默认执行所有资产项操作，若有选择则执行选中资产项的相关操作(例如：部署、生成构建配置等操作)。
                    </span>
                </div>
                <el-table 
                    :data="assetslist" 
                    ref="assetsTable" 
                    border 
                    @selection-change="handleSelectionChange" 
                    style="width:auto;font-size:13px;">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="name" label="资产名称" width="200"></el-table-column>
                    <el-table-column prop="code" label="资产编码" width="200"></el-table-column>
                    <el-table-column prop="outer_ip" label="外网IP" width="150"></el-table-column>
                    <el-table-column prop="lan_ip" label="内网IP" width="150"></el-table-column>
                    <el-table-column prop="user" label="用户名" width="80"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <div class="tab-btns">
                                <el-button 
                                    class="btn-item" 
                                    @click="serverConfigs(scope.row)"
                                    size="small"
                                    type="primary" size="mini">脚本任务</el-button>
                                <div v-for="(item,index) in tasklist" :key="index">
                                    <el-button 
                                        class="btn-item" 
                                        @click="deployApplications(item, 3, scope.row)" 
                                        :type="item.btntype" 
                                        size="small"
                                        size="mini">{{item.task_name}}</el-button>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
    </div>
    <!-- main -->
    <div class="config_main mt30" v-for="(item,index) in tasklist" :key="index">
        <div class="item_task">
            <div class="title">{{item.task_name}}</div>
            <el-row class="mt30">
                <el-col :span="12">
                    <div class="block">
                        <div class="left">任务类型</div>
                        <div class="right">
                            {{item.task_type=='git'?'git hooks任务':''}}
                            {{item.task_type=='shell'?'shell脚本任务':''}}
                            {{item.task_type=='command'?'命令行运行任务':''}}
                        </div>
                    </div>
                </el-col>
                <el-col :span="12" v-if="item.task_type!='command'?true:false">
                    <div class="block">
                        <div class="left">git部署方式</div>
                        <div class="right">{{item.task_type=='git'?'https方式':''}}{{item.task_type=='ssh'?'ssh方式':''}}</div>
                    </div>
                </el-col>
            </el-row>
            <div v-if="item.task_type!='command'?true:false">
                <el-row class="mt20">
                    <el-col :span="12">
                        <div class="block">
                            <div class="left">shell脚本路径</div>
                            <div class="right">{{item.shell_path}}</div>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="block">
                            <div class="left">shell脚本参数</div>
                            <div class="right">{{item.shell_opction}}</div>
                        </div>
                    </el-col>
                </el-row>
                <el-row class="mt20">
                    <el-col :span="12">
                        <div class="block">
                            <div class="left">shell脚本运行命令</div>
                            <div class="right">{{'sh ' + item.shell_path +' '+ (item.shell_opction?item.shell_opction:'')}}</div>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="block">
                            <div class="left">shell脚本上传方式</div>
                            <div class="right">
                                {{item.shell_write_type == 1 ? '新建文件并上传方式' :''}}
                                {{item.shell_write_type == 2 ? 'shell窗口命令行创建方式' :''}}
                            </div>
                        </div>
                    </el-col>
                </el-row>
                <el-row class="mt20">
                    <el-col :span="12">
                        <div class="block">
                            <div class="left">发布前是否先做备份</div>
                            <div class="right">
                                <el-switch v-model="item.is_backups"></el-switch>
                            </div>
                        </div>
                    </el-col>
                </el-row>
                <el-row class="mt20">
                    <el-col :span="12">
                        <div class="block">
                            <div class="left">需要备份的资源</div>
                            <div class="right">{{item.project_path}}</div>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="block">
                            <div class="left">备份文件的存放位置</div>
                            <div class="right">{{item.backups_path}}</div>
                        </div>
                    </el-col>
                </el-row>
            </div>
            <el-row class="mt20" v-if="item.remarks?true:false">
                <el-col :span="24">
                    <div class="block">
                        <div class="left">备注</div>
                        <div class="right">{{item.remarks}}</div>
                    </div>
                </el-col>
            </el-row>
            <div class="block mt30">
                <div class="left">shell脚本内容</div>
                <div class="right">
                    <div :id="'editor_'+index" class="comm_build_textarea" :style="{height:item.task_type=='command'?'40px':'300px'}"></div>
                </div>
            </div>
            <div class="ml10 mt30 light tc" v-if="item.task_type!='command'?true:false">
                <i class="el-icon-warning fs-16 mr5 primary"></i>
                请确保已生成构建配置，若未生成构建配置，则先执行生成构建配置按钮，再执行部署任务。
            </div>
            <div class="btns mb20">
                <el-button 
                    type="primary" 
                    @click="deployApplications(item,1)">
                    {{item.task_type=='command'?'开始运行':'开始部署'}}
                </el-button>
                <el-button 
                    v-if="item.task_type!='command'?true:false" 
                    type="success" 
                    @click="backupApplications(item)" plain>
                    服务备份
                </el-button>
                <el-button 
                    v-if="item.task_type!='command'?true:false" 
                    type="danger" @click="generateBuildConfig(item)" plain>
                    生成构建配置
                </el-button>
                <el-button 
                    type="primary" 
                    @click="updageAppConfigs(index)" plain>
                    修改构建配置
                </el-button>
                <el-button type="default" @click="goBack">返回</el-button>
            </div>
        </div>
    </div>

    <!-- 开始构建 -->
    <el-dialog class="build_product" :title="buildLogs.task_name" :fullscreen="true" :close-on-click-modal="false" :visible.sync="dialogTableVisible">
        <div class="build_content">
            <div class="top" v-if="taskType!=='command'">
                <el-table class="table" border max-height="250" :data="buildLogs.content">
                    <el-table-column property="assets_name" label="资产名称" width="200"></el-table-column>
                    <el-table-column property="outer_ip" label="外网IP" width="180"></el-table-column>
                    <el-table-column property="lan_ip" label="内网IP" width="150"></el-table-column>
                    <el-table-column label="构建状态" width="200">
                        <template slot-scope="scope">
                            <div v-if="scope.row.code==-100" class="red"><i class="el-icon-loading"></i> 应用构建中...</div>
                            <div v-if="scope.row.code!=-100" :class="scope.row.code==0?'success':'red'">
                                {{scope.row.code==0?'构建成功':'构建失败'}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column property="shell" label="执行shell内容"></el-table-column>
                </el-table>
            </div>
            <div class="bottom mt30">
                <div class="navs">
                    <el-tabs v-model="activeName">
                        <el-tab-pane v-for="(item,index) in assetslist" :label="item.name+'-'+item.outer_ip" :name="index+''"></el-tab-pane>
                    </el-tabs>
                </div>
                <div class="shell-terminal">
                    <div class="terminal" v-for="(item,index) in assetslist" :key="index" :style="{zIndex:activeName==index?10:1}"
                        :id="'terminal'+index"></div>
                </div>
            </div>
        </div>
    </el-dialog>

    <!-- 备份|构建日志 -->
    <el-dialog width="80%" :title="logsData.task_name" :visible.sync="dialogModelVisible">
        <!-- <div></div> -->
        <el-table :data="logsData.content">
            <el-table-column property="assets_name" label="资产名称" width="200"></el-table-column>
            <el-table-column property="outer_ip" label="外网IP" width="150"></el-table-column>
            <el-table-column property="lan_ip" label="内网IP" width="100"></el-table-column>
            <el-table-column label="执行状态" width="100">
                <template slot-scope="scope">
                    <div v-if="scope.row.code==-100"><i class="el-icon-loading"></i> 构建中...</div>
                    <div 
                        v-if="scope.row.code!=-100"
                        :class="scope.row.code==0?'success':'red'">
                        {{scope.row.code==0?'执行成功':'执行失败'}}
                    </div>
                </template>
            </el-table-column>
            <el-table-column v-if="logsData.type===2 || logsData.type===1" property="shell" label="执行shell内容"></el-table-column>
            <el-table-column v-if="logsData.type!==1" property="data" label="执行日志"></el-table-column>
        </el-table>
    </el-dialog>

</div>
<script>var require = { paths: { 'vs': 'https://cdn.bootcss.com/monaco-editor/0.16.2/min/vs' } };</script>
<script src="//cdn.bootcss.com/monaco-editor/0.16.2/min/vs/loader.js"></script>
<script>
    let xteamlist = null;
    let socket = null;
    new Vue({
        el: '#team',
        data: function () {
            return {
                id: util.getQueryString('id'),
                assetslist: [],
                dialogTableVisible: false,
                tasklist: [],
                multipleSelection:[],
                type:'',
                shell_model_item: 0,
                model_icon:1,
                taskName:'',
                dialogModelVisible:false,
                logsData: { content:[] },
                configLogs:{},
                backupLogs:{},
                buildLogs:{},
                activeName: '0',
                taskType:'git',
            }
        },
        mounted() {
            this.buildListEnd = [];
            this.itemdetail();
            this.fullscreen();
        },
        methods: {
            runMonaco(id, data){
                //载入Monaco
                let editor = null;
                const _this = this;
                const moId = `editor_${id}`;
                require(['vs/editor/editor.main'], function () {
                    //得到支持的语言
                    var modesIds = monaco.languages.getLanguages().map(function (lang) { return lang.id }).sort();
                    //创建编辑器
                    editor = monaco.editor.create(document.getElementById(moId), {
                        //内容
                        value: data,
                        //语言
                        language: 'shell',
                        scrollBeyondLastLine: false,
                        readOnly: true,
                        automaticLayout: true,
                        //主题，三款：vs、vs-dark、hc-black
                        theme: 'vs-dark',
                        //代码略缩图
                        minimap: {
                            enabled: false
                        }
                    });
                });
            },
            itemdetail() {
                util.ajax({
                    type: 'get',
                    url: `${config.baseApi}api/v1/application/itemdetail`,
                    data: {
                        id: this.id,
                    },
                    success: data => {
                        this.assetslist = data.data.assets_list || [];
                        const tasklist = data.data.task_list || [];
                        if (tasklist && tasklist.length) {
                            tasklist.forEach((item, index) => {
                                item.btntype = index % 3 == 0 ? 'danger' : '' + index % 2 == 0 ? 'primary' : '' + index % 1 == 0 ? 'success' : '';
                                item.is_backups = item.is_backups == 1 ? true : false;
                                this.runMonaco(index, item.shell_body)
                            })
                        }
                        this.tasklist = tasklist;
                        const assetsId = util.getQueryString('assetsId');
                        setTimeout(() => { 
                            if(assetsId){
                                this.assetslist.forEach(item => {if(assetsId == item._id) this.$refs.assetsTable.toggleRowSelection(item, true)})
                            }else{
                                this.assetslist.forEach(item => {this.$refs.assetsTable.toggleRowSelection(item, true);})
                            }
                        })
                    }
                })
            },
            goBack() {
                location.href = "/build"
            },
            deployApplications(taskItem, type, assetsItem) {
                if (!taskItem.shell_path && taskItem.task_type != 'command') {
                    popup.alert({ title: 'shell脚本路径不能为空!' })
                    return;
                }
                if (!taskItem.shell_body) {
                    popup.alert({ title: 'shell脚本内容不能为空!' })
                    return;
                }

                if(!this.multipleSelection.length){
                    popup.alert({title:'请先勾选需要部署的服务器!'});
                    return;
                }

                let startType = '';

                if(!xteamlist) {
                    // 第一次点击发布
                    startType = 'new';
                } else if(type === this.type && this.taskName === taskItem.task_name && xteamlist){
                    // 第二次点击发布
                    startType = 'agein';
                } else if(type !== this.type && this.taskName !== taskItem.task_name && xteamlist) {
                    // 切换了发布方式
                    startType = 'switch';
                }

                this.type = type;
                this.taskName = taskItem.task_name;
                this.taskType = taskItem.task_type;
                // 弹出框
                this.dialogTableVisible = true;
                if(!this.buildLogs.task_name){
                    const assetslist = [];
                    this.assetslist.forEach(item => {
                        assetslist.push({
                            assets_name: item.name,
                            code: -100,
                            data: '',
                            lan_ip: item.lan_ip,
                            outer_ip: item.outer_ip,
                            shell: taskItem.shell_path ? 'sh ' + taskItem.shell_path : '',
                        })
                    })
                    this.buildLogs = {
                        task_name: taskItem.task_name + '任务-构建应用服务',
                        type: 1,
                        content: assetslist,
                    }
                }

                setTimeout(()=>{
                    let assetsList = this.multipleSelection;
                    if(type === 3) assetsList = [assetsItem];

                    // 开始
                    const result = util.startSocketXteam({
                        id: this.id,
                        buildType: 'buildprocess',
                        taskItem,
                        assetsList,
                        startType,
                        callback: this.callback,
                    });
                    socket = result.socket;
                    xteamlist = result.xteamList;
                })
            },
            callback(data = {}){
                this.buildListEnd.push(1);
                if(!this.buildLogs.date) this.buildLogs.date = data.date || new Date();
                this.buildLogs.content[data.index].code = data.isSuccess ? 0 : 1;

                // 构建完成
                if(this.buildListEnd.length === this.buildLogs.content.length){
                    this.buildApplicationed();
                }
            },
            buildApplicationed(){
                this.buildLogs.application_id = this.id;
                util.ajax({
                    nohideloading: true,
                    url: `${config.baseApi}api/v1/build/buildApplicationed`,
                    data: this.buildLogs,
                    success: data => {}
                })
            },
            backupApplications(item = {}){
                if(!item.project_path){
                    popup.alert({title:'需要备份的资源|目录不能为空!'})
                    return;
                }
                if (!item.backups_path) {
                    popup.alert({ title: '备份文件的存放位置不能为空!' })
                    return;
                }

                this.dialogModelVisible = true;
                if (this.backupLogs.isLoad) {
                    this.logsData = this.backupLogs;
                    return;
                }

                const assetslist = [];
                this.assetslist.forEach(item => {
                    assetslist.push({
                        assets_name: item.name,
                        code: -100,
                        data: '',
                        lan_ip: item.lan_ip,
                        outer_ip: item.outer_ip,
                    })
                })
                this.backupLogs = this.logsData = {
                    task_name: item.task_name + '任务-服务备份',
                    type: 3,
                    content: assetslist,
                }
                let userMsg = util.getStorage('local', 'userMsg');
                let user_name = userMsg ? JSON.parse(userMsg).user_name : '';
                util.ajax({
                    nohideloading: true,
                    notimeout: true,
                    url: `${config.baseApi}api/v1/build/backupApplications`,
                    data: {
                        id: this.id,
                        taskItem: item,
                        user_name,
                        assetsList: this.assetslist,
                    },
                    success: data => {
                        this.backupLogs = this.logsData = data.data || {};
                    }
                })
            },
            handleShellModel(type){
                if(type === 3){
                    if(this.model_icon === 1){
                        this.model_icon = 2;
                        type = 3;
                    }else{
                        this.model_icon = 1;
                        type = 4;
                    }
                }
                util.setSocketXteam(type, xteamlist, socket);
            },
            generateBuildConfig(item){
                if (!item.shell_path) {
                    popup.alert({ title: 'shell脚本路径不能为空!' })
                    return;
                }
                if (!item.shell_body) {
                    popup.alert({ title: 'shell脚本内容不能为空!' })
                    return;
                }

                this.dialogModelVisible = true;
                if(this.configLogs.isLoad){
                    this.logsData = this.configLogs;
                    return;
                }

                const assetslist = [];
                this.assetslist.forEach(item=>{
                    assetslist.push({
                        assets_name: item.name,
                        code: -100,
                        data: '',
                        lan_ip: item.lan_ip,
                        outer_ip: item.outer_ip,
                    })
                })
                this.configLogs = this.logsData = {
                    task_name: item.task_name + '任务-生成构建配置',
                    type: 3,
                    content: assetslist,
                }
                let userMsg = util.getStorage('local', 'userMsg');
                let user_name = userMsg ? JSON.parse(userMsg).user_name : '';
                util.ajax({
                    nohideloading:true,
                    notimeout: true,
                    url: `${config.baseApi}api/v1/build/generateBuildConfig`,
                    data: {
                        id: this.id,
                        taskItem: item,
                        user_name,
                        assetsList:this.assetslist,
                    },
                    success: data => {
                        this.configLogs = this.logsData = data.data || {};
                    }
                })
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            serverConfigs(item) {
                if (!item && !this.multipleSelection.length) {
                    popup.alert({ title: '请选择需要配置的资产!' })
                    return;
                }
                const assestsList = item ? [item] : this.multipleSelection;
                util.setStorage('session', 'assets_list_configs', JSON.stringify(assestsList));
                location.href = "/assetsconfig";
            },
            updageAppConfigs(index){
                location.href = "/appconfig?id="+this.id+'&tab='+index;
            },
            applicationConsole(){
                if (!this.multipleSelection.length) {
                    popup.alert({ title: '请选择进入控制台的资产列表!' })
                    return;
                }
                let ids = '';
                this.multipleSelection && this.multipleSelection.forEach(item => {
                    ids = ids + item._id + ','
                })
                ids = ids ? ids.slice(0, -1) : '';
                window.open("/console?ids=" + ids);
            },
            fullscreen() {
                const _this = this;
                $(document).keyup(function (event) {
                    console.log(event.keyCode)
                    if (event.keyCode === 112) {
                        if (xteamlist && xteamlist[_this.activeName]) {
                            xteamlist[_this.activeName].toggleFullScreen();
                        }
                    }
                });
            },
        }
    })
</script>